package com.xdw.addressbookbyjava;

import ohos.aafwk.ability.AbilityPackage;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.data.DatabaseHelper;
import ohos.data.rdb.RdbOpenCallback;
import ohos.data.rdb.RdbStore;
import ohos.data.rdb.StoreConfig;

public class MyApplication extends AbilityPackage {
    //该项目案例开发了两个版本进行演示，一个无数据库的静态数据版本，一个带数据库操作的sqlite版本
    public static final int STATIC_DATA_VERSION =1;
    public static final int SQLITE_DATA_VERSION =2;
    //定义DEV_DATA_VERSION，通过切换该版本号来快速切换静态数据版和数据库版本
    public static final int DEV_DATA_VERSION = SQLITE_DATA_VERSION;
    private static RdbStore store;  //在入口类中定义store对象，用来进行sqlite api操作的关键对象
    private static final RdbOpenCallback callback = new RdbOpenCallback() {
        @Override
        public void onCreate(RdbStore store) {
            store.executeSql("CREATE TABLE IF NOT EXISTS contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, gender INTEGER,phone TEXT NOT NULL, groupId INTEGER)");
        }

        @Override
        public void onUpgrade(RdbStore store, int oldVersion, int newVersion) {
        }
    };

    @Override
    public void onInitialize() {
        super.onInitialize();
        Intent intent2 = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("com.example.wdproject")
                .withAbilityName("com.xdw.addressbookbyjava.ContactsServiceAbility")
                .build();
        intent2.setOperation(operation);
        startAbility(intent2,1);
        //在程序入口处初始化数据库信息
        StoreConfig config = StoreConfig.newDefaultConfig("RdbContacts.db"); //RdbContacts.db为数据库名称，不存在则自动创建
        DatabaseHelper helper = new DatabaseHelper(this);
        store = helper.getRdbStore(config, 1, callback, null);  //生成store对象
    }

    /**
     * 定义获取store对象的方法，后面可以随时调用进行数据库相关操作
     *
     * @return
     */
    public static RdbStore getRdbStore() {
        return store;
    }
}
